<?php

namespace App\Service\VendorClient\Shoplasa;

use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

/**
 * 拉萨上游对接
 * @author: hj
 */
class ShoplasaApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shoplasa';

    //配置文件
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     */
    public function createOrder($param = []) {
        if (empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo'])) {
            return Normal::returnCode(Normal::FAIL, "except param supplierOrder or orderGoods or order or binfo");
        }
        $orderInfo = $param['supplierOrder'];
        $goodsList = $param['orderGoods'];
        $order     = $param['order'];
        $binfo     = $param['binfo'];
        $order_sn  = $orderInfo['supplier_dsn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //优惠
        $discount_money = $orderInfo['discount_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //用户实际支付金额
        $real_total_money = $orderInfo['real_total_money'];
        //支付公司和电商平台
        $payCommanyCode = isset($apply_extends['payCommanyCode']) && !empty($apply_extends['payCommanyCode']) ? $apply_extends['payCommanyCode'] : '';
        $payCommanyCode = isset($order['payCommanyCode']) && !empty($order['payCommanyCode']) ? $order['payCommanyCode'] : $payCommanyCode;
        $payCommanyName = isset($apply_extends['payCommanyName']) && !empty($apply_extends['payCommanyName']) ? $apply_extends['payCommanyName'] : '';
        $payCommanyName = isset($order['payCommanyName']) && !empty($order['payCommanyName']) ? $order['payCommanyName'] : $payCommanyName;
        try {
            $payWay = ServiceConfig::instance()->getConfigByEventsValue(self::SUPPLIER_CODE, ServiceConfig::TYPE_PAY, $payCommanyCode);
        } catch (\Throwable $th) {
            return Normal::returnCode(Normal::FAIL, "支付方式获取异常：【{$th->getMessage()}】");
        }
        if (empty($payWay)) {
            return Normal::returnCode(Normal::FAIL, "支付公司：【{$payCommanyName}】未映射，请联系管理员处理");
        }
        $paySerial      = isset($apply_extends['paySerial']) && !empty($apply_extends['paySerial']) ? $apply_extends['paySerial'] : '';
        $paySerial      = isset($order['paySerial']) && !empty($order['paySerial']) ? $order['paySerial'] : $paySerial;
        $enterpriseNum  = isset($apply_extends['enterpriseNum']) && !empty($apply_extends['enterpriseNum']) ? $apply_extends['enterpriseNum'] : '';
        $enterpriseNum  = isset($order['enterpriseNum']) && !empty($order['enterpriseNum']) ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = isset($apply_extends['enterpriseName']) && !empty($apply_extends['enterpriseName']) ? $apply_extends['enterpriseName'] : '';
        $enterpriseName = isset($order['enterpriseName']) && !empty($order['enterpriseName']) ? $order['enterpriseName'] : $enterpriseName;

        //商品总金额
        $goodsTotalMoney = '0.00';
        $palceOrderGoods = [];
        foreach ($goodsList as $key => $item) {
            $tax_rate         = bcadd('1', (string)$item['tax_rate'], 4);
            $price            = $item['price'];
            $spec_num         = $item['spec_num'];
            $quantity         = $item['quantity'];
            $supplier_skucode = $item['supplier_skucode'];
            $goods_type       = $item['goods_type'];
            $weight           = $item['weight'] ? bcdiv((string)($item['weight']), '1000', 2) : '0';
            //下单商品组
            $goodsInfo       = [
                'goodInfoItemNo'    => trim($item['supplier_skucode']),//货号
                'goodsInfoName'     => $item['goods_name'],//商品名称,
                'goodsInfoSubtitle' => $item['goods_name'],//货品副标题,
                'goodsInfoNum'      => $quantity,//货品个数,
                'goodsInfoPrice'    => $price,//货品交易价格,
                'hsCode'            => trim($item['supplier_skucode']),//海关编码（HS编码）
                'gdsMtNo'           => trim($item['supplier_skucode']),//商品料号
            ];
            $goodsMoneyRow   = bcmul((string)$price, (string)$quantity, 2);
            $goodsTotalMoney = bcadd($goodsTotalMoney, $goodsMoneyRow, 2);

            $palceOrderGoods[] = $goodsInfo;
        }
        $orderMoney    = bcadd($goodsTotalMoney, (string)$deliver_money, 2);
        $discountMoney = bcsub($orderMoney, (string)$real_total_money, 2);
        $requestParam  = [
            [
                'orderCode'            => $order_sn,//订单编号
                'orderPrice'           => $real_total_money,//订单金额 实付金额
                'appTime'              => date('Y-m-d H:i:s', time()),//申报时间，如果没有，填当前时间
                'orderPrePrice'        => $discountMoney > 0 ? $discountMoney : '0.00',//订单优惠金额
                'orderOldPrice'        => $orderMoney,//订单原始总金额 商品金额+运费
                'orderStatus'          => '1',//订单状态0 未付款 1 已付款未发货 2 已发货 3 已经收货
                'payTime'              => $pay_time,//支付时间
                'shippingProvince'     => $orderInfo['province'],//收货省
                'shippingCity'         => $orderInfo['city'],//收货市
                'shippingCounty'       => $orderInfo['district'],//收货区县
                'shippingAddress'      => $orderInfo['receive_address'],//收货详细地址
                'shippingPerson'       => $orderInfo['receive_name'],//收货人
                'shippingPhone'        => $orderInfo['recveive_phone'],//收货电话，如果没有，填“无
                'shippingMobile'       => $orderInfo['recveive_phone'],//收货手机
                'customerRemark'       => $orderInfo['order_remark'] ?? '',//客户留言
                'payId'                => $payWay,//支付方式 1-支付宝 3-微信
                'orderNewStatus'       => '0',//是否是新增订单 0 新增订单 1 已查看订单
                'orderExpressType'     => '1',//配送方式，默认“1”
                'orderLinePay'         => '1',//1在线支付 0货到付款
                'tradeType'            => '4',//订单贸易类型：1:一般贸易 2：跨境直邮 3：保税集货 4保税备货
                'omsPushStatus'        => '0',//运单状态：'0':未申报,'1'：申报成功,'2'：推送失败
                'orderPushStatus'      => '0',//订单推送海关状态：'0':未推送,'1'：'订单报文以生成','2':订单推送成功 '3'：订单推送失败
                'payPushStatus'        => '1',//支付单状态：'0':未申报,'1'：申报成功,'2'：申报失败 3-申报中
                'orderBizType'         => '0',//订单业务类型0普通订单1拼团订单
                'combinedPay'          => '0',//是否合并支付， 0单笔支付 1合并支付
                'alipayDeclareNo'      => $paySerial,//支付宝报关流水号，没有可填无 其它支付方式也填到这
                'orderDeclarStatus'    => '0',//订单申报状态：'0':未申报,'1':已申报,'2'：申报成功,'3'：申报失败
                'userMobile'           => $orderInfo['buyer_phone'],//订购人电话
                'customerUsername'     => $orderInfo["buyer_realname"],//订购人姓名
                'infoCardNo'           => $orderInfo["buyer_idcard"],//订购人身份证号
                'ebpCode'              => $enterpriseNum,//电商平台编码
                'ebpName'              => $enterpriseName,//电商企业名称
                'bondedOrderGoodsList' => $palceOrderGoods,//订购人电话
            ]
        ];
        $data          = [
            'method' => 'createOrder',
            'data'   => $requestParam,
        ];
        return $this->execute($data);
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function sign($data) {
        //Java 版本相同的 AES 算法（AES/ECB/PKCS5Padding）来加密数据。
        // return base64_encode(openssl_encrypt(json_encode($data, JSON_UNESCAPED_UNICODE), 'AES-128-ECB', $this->config["aesKey"], OPENSSL_RAW_DATA));
        $key = $this->config["aesKey"];
        $ase_key =substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $iv = '';
        $encrypted = openssl_encrypt(json_encode($data, JSON_UNESCAPED_UNICODE),'AES-128-ECB',$ase_key,OPENSSL_RAW_DATA,$iv);
        return base64_encode($encrypted);
    }

    /**
     * CURL请求
     * @param $param
     * @return array
     */
    public function execute($param = []) {
        if (!isset($this->config[$param['method']])) {
            return Normal::returnCode(Normal::FAIL, "请求路由未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        $url = $this->config[$param['method']];
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        $pushData = [
            'data' => $this->sign($param["data"]),
        ];
        $parameter = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'json',
                'header' => [],
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $result  = @json_decode($resTask['response']['result'], true);
        if (isset($result['code']) && $result['code'] == 0) {
            return Normal::returnCode(Normal::SUC, "请求成功", $result);
        } else {
            $msg = $result['message'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg, $result);
        }
    }
}